package com.lld.im.service.utils;

import com.lld.im.common.config.AppConfig;
import com.lld.im.common.constants.Constants;
import com.lld.im.common.enums.ClientType;
import com.lld.im.common.enums.UserErrorCode;
import com.lld.im.common.exception.ApplicationException;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

public class ZKKit {

    private AppConfig appConfig;
    private ZkClient zkClient ;

    public ZKKit(AppConfig appConfig) {
        this.appConfig = appConfig;
        init();
    }

    public  void init(){
         zkClient=new ZkClient(appConfig.getZkAddr(), appConfig.getZkConnectTimeOut());
    }

    /**
     * 获得注册 在zk中的服务
     * @param clientType
     * @return
     */
    public List<String> getServers(Integer clientType){
        List<String> children;
        /* web端返回websocket服务 */
        if(clientType== ClientType.WEB.getCode()){
            String webRootPath= Constants.ImCoreZkRoot+Constants.ImCoreZkRootWeb;
            children= zkClient.getChildren(webRootPath);
        }else {
            String tcpRootPath=Constants.ImCoreZkRoot+Constants.ImCoreZkRootTcp;
            children = zkClient.getChildren(tcpRootPath);
        }
        if(children.isEmpty())
            throw new ApplicationException(UserErrorCode.SERVER_NOT_AVAILABLE);
        return children;
    }




}
